﻿using AutoMapper;
using MediatR;
using ProcurementManagement.Applcation.Command.ProcureEnquiryCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcureEnquiryCommandHandlers
{
    /// <summary>
    /// 采购询价修改
    /// </summary>
    public class ProcureEnquiryUpdateCommandHandlers : IRequestHandler<ProcureEnquiryUpdateCommand, int>
    {
        protected readonly IProcureEnquiryRepository repository;
        protected readonly IInquiryVendorRepository vendorRepository;
        protected readonly IMapper mapper;
        protected readonly ISqlSugarClient db;

        public ProcureEnquiryUpdateCommandHandlers(IProcureEnquiryRepository repository, IInquiryVendorRepository vendorRepository, IMapper mapper, ISqlSugarClient db)
        {
            this.repository = repository;
            this.vendorRepository = vendorRepository;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(ProcureEnquiryUpdateCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {
                await repository.UpdataAsync(mapper.Map<ProcureEnquiry>(request.Pdto));
                var repLiist = (await vendorRepository.GetAll()).Where(x => x.PEDocumentsNumber == request.Pdto.PEDocumentsNumber).ToList();
                //先删除
                await vendorRepository.DelRange(repLiist);
                //再添加
                foreach (var item in request.Pdto.dtos)
                {
                    InquiryVendor vendor = new InquiryVendor
                    {
                        VendorName = item.VendorName,
                        VendorNum = item.VendorNum,
                        VendorPrice = item.VendorPrice,
                        SumPrice = item.SumPrice,
                        DeliveryDate = item.DeliveryDate,
                        AddName = request.Pdto.AddName,
                        AddTime = request.Pdto.AddTime,
                        UpdName = request.Pdto.UpdName,
                        UpdTime = request.Pdto.UpdTime,
                        DelName = request.Pdto.DelName,
                        DelTime = request.Pdto.DelTime,
                        PEDocumentsNumber = request.Pdto.PEDocumentsNumber,
                        Office_Id = request.Pdto.Office_Id,
                        User_Id = request.Pdto.User_Id,
                       
                    };
                    await vendorRepository.AddAsync(vendor);
                }
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }

        }
    }
}
